from django.shortcuts import render, redirect
from django.urls import reverse
from django.http.response import JsonResponse
import string
import random
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.decorators import login_required

User = get_user_model()


# Create your views here.
@require_http_methods(["GET", "POST"])
def mylogin(request):
    if request.method == "GET":
        return render(request, "myauth/login.html")
    else:
        form = LoginForm(request.POST)
        checkTag = form.is_valid()
        context = {
            "userInfo": {
                "email": request.POST.get("email"),
                "password": request.POST.get("password"),
                "remember": request.POST.get("remember"),
            },
        }
        if checkTag:
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            remember = form.cleaned_data.get("remember")
            user = User.objects.filter(email=email).first()
            if user:
                if user.check_password(password):
                    # 登录
                    login(request, user)
                    # 判断是否记住我
                    if not remember:
                        # 如果没有勾选记住我，就设置过期时间0,即浏览器关闭就过期
                        request.session.set_expiry(0)
                    # 如果记住我，就使用默认过期时间2周
                    return redirect("/myblog/index")
                else:
                    context["err"] = {"password": [{"message": "密码错误", "code": ""}]}
                    print(f"login-context-1:{context}")
                    return render(request, "myauth/login.html", context=context)
            else:
                context["err"] = {"email": [{"message": "邮箱不存在", "code": ""}]}
                print(f"login-context-1:{context}")
                return render(request, "myauth/login.html", context=context)
        else:
            formErr = form.errors.get_json_data()
            context["err"] = formErr
            print(f"login-context-2:{context}")
            return render(request, "myauth/login.html", context=context)


def mylogout(request):
    logout(request)
    return redirect("/myblog/index")


@require_http_methods(["GET", "POST"])
def register(request):
    if request.method == "GET":
        return render(request, "myauth/register.html")
    else:
        form = RegisterForm(request.POST)

        checkTag = form.is_valid()
        if checkTag:
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            # captcha=form.cleaned_data.get('captcha')
            password = form.cleaned_data.get("password")

            User.objects.create_user(email=email, username=username, password=password)
            return redirect(reverse("myauth:login"))
        else:
            formErr = form.errors.get_json_data()

            context = {
                "userInfo": {
                    "username": request.POST.get("username"),
                    "email": request.POST.get("email"),
                    "captcha": request.POST.get("captcha"),
                    "password": request.POST.get("password"),
                },
                "err": formErr,
            }
            print(f"register-context:{context}")
            # return redirect(reverse('myauth:register'))
            return render(request, "myauth/register.html", context=context)


def send_email_captcha(request):
    # ?email=xxx
    email = request.GET.get("email")
    if not email:
        return JsonResponse({"code": 400, "message": "必须传递邮箱！"})
    # 生成验证码（取随机的阿拉伯数字）
    # ['0','3','1','2']=>'0312'
    captcha = "".join(random.sample(string.digits, 4))
    # 存储到数据库中
    CaptchaModel.objects.update_or_create(email=email, defaults={"captcha": captcha})
    # 邮件发送 需使用异步，防止阻塞
    send_mail(
        "我的博客注册验证码",
        message=f"您的注册验证码是：{captcha}",
        recipient_list={email},
        from_email=None,
    )

    return JsonResponse({"code": 200, "message": "邮箱验证码发送成功！"})


@login_required()
def my_info(request):
    return render(request, "myauth/my_info.html")
